<template>
  <h3>后台首页</h3>
  <el-form :model="formData">
    <el-form-item label="书籍名称:" label-width="100">
      <el-input v-model="formData.bookName" style="width: 20vw"></el-input>
    </el-form-item>
    <el-form-item label="书籍作者:" label-width="100">
      <el-input v-model="formData.bookAuthor" style="width: 20vw"></el-input>
    </el-form-item>
    <el-form-item label="书籍类型:" label-width="100">
      <el-select v-model="formData.bookType" placeholder="请选择书籍的类型" style="width: 20vw">
        <el-option label="动漫幽默" value="1"/>
        <el-option label="专业课书籍" value="2"/>
        <el-option label="自然类学科" value="3"/>
        <el-option label="人文类学科" value="4"/>
      </el-select>
    </el-form-item>
    <el-form-item label="书籍描述:" label-width="100">
      <el-input v-model="formData.bookDescribe" type="textarea" style="width: 20vw"></el-input>
    </el-form-item>
    <el-form-item label="书籍数量:" label-width="100">
      <el-input v-model="formData.bookAmount" placeholder="请输入书籍数量[0-120]" style="width: 20vw"></el-input>
    </el-form-item>
    <el-form-item label="书籍封面:" label-width="100">
      <el-upload
          :http-request="httpRequest"
          multiple
          :show-file-list="true"
          list-type="picture-card"
      ><el-icon><Plus /></el-icon>
      </el-upload>
    </el-form-item>
    <div>
      <el-button>取消</el-button>
      <el-button type="primary" @click="onBtn">添加</el-button>
    </div>
  </el-form>
</template>

<script setup>
import {ref, reactive} from "vue";
import axios from "axios";
import { Plus } from '@element-plus/icons-vue'

const formData = reactive({
  bookName: '',
  bookAuthor: '',
  bookType: '',
  bookDescribe: '',
  bookAmount: '',
});

//定义一个响应式数组用来接收图片
const fileList = ref([])

//自定义函数用来覆盖原有的XHR行为（默认提交行为）
function httpRequest(option) {
//将图片存到数组中
  fileList.value.push(option)
}

async function onBtn() {
  let dataForm = new FormData();
  dataForm.append('bookName', formData.bookName)
  dataForm.append('bookAuthor', formData.bookAuthor)
  dataForm.append('bookType', formData.bookType)
  dataForm.append('bookDescribe', formData.bookDescribe)
  dataForm.append('bookAmount', formData.bookAmount)

//将图片的二进制通过表单的形式发送到后台
  fileList.value.forEach((it,index)=>{
    dataForm.append('filename',it.file)
  })
  await axios({
    method: 'POST',
    url: 'http://localhost:1234/U',
    data: dataForm,
//设置请求参数的规则
    headers: {
      "Content-Type": "multipart/form-data"
    }
  }).then(response => {
    console.log(response.data)
  })
}
</script>